package rmhc.api.vk
{
	import com.adobe.images.PNGEncoder;
	import com.adobe.serialization.json.JSON;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import rmhc.api.tasks.ISetProfilePicture;
	import rmhc.gui.customTrace;
	import rmhc.gui.SupplyFunctions;
	import rmhc.server.FileUploader;
	
	import rmhc.api.tasks.IUploadProfilePhoto;
	
	public class UploadProfilePhoto extends VkApiTask implements ISetProfilePicture
	{
		private var url:String;
		private var upl:FileUploader;
		private var photo:BitmapData;
		private var ready:Boolean = false;
		private var photoID:String;
		public function UploadProfilePhoto(wrapper:VkApi,photo:BitmapData,uploadURL:String)
		{
			url = uploadURL;
			customTrace("UploadProfilePhoto:UploadProfilePhoto:" );
			upl = new FileUploader( url );
			super(wrapper, "photos.saveProfilePhoto");
			this.photo = photo;			
		}
		
		private function upl_complete(e:Event):void 
		{
			ready = true;
			var resp:Object = JSON.decode( upl.data );
			customTrace("UploadProfilePhoto:upl_complete:" + SupplyFunctions.objectToString(resp) );
			//[ resp : mid='313201' photo='' hash='03c2c1a63c0679fd6b3287df83681193' profile_aid='-6' server='11511' message_code='7' ]
			params['server'] = resp['server'];
			params['photo'] = resp['photo'];
			photoID = resp['photo'];
			params['hash'] = resp['hash'];
			wrapper.addTask(this);
			super.run();
		}
		
		private function onPhotoUploaded(e:Event):void 
		{
			customTrace("UploadProfilePhoto:onPhotoUploaded:" +SupplyFunctions.objectToString(JSON.decode(upl.data))); 
		}
		override public function run():void 
		{
			customTrace("UploadProfilePhoto:run:" );
			var ba:ByteArray = PNGEncoder.encode(photo);;
			upl.addFile( "photo" , "photo.png" , ba , "image/png" );
			upl.addEventListener( Event.COMPLETE , upl_complete);
			upl.load(null);
		}
		override public function getMethod():String 
		{
			if (!ready)
				return null;
			return super.getMethod();
		}
	 	public function getPhotoId():String {
			return photoID;
		}
		override public function parseData(result:Object):void
		{
			customTrace("UploadProfilePhoto:parseData:" + SupplyFunctions.objectToString(result));
			customTrace("UploadProfilePhoto:parseData: return;!!!" );
			onComplete();
		}
	}
}